package com.syncnote.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

//import org.springframework.mvc.extensions.ajax.AjaxUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
//import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
//import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class fileUploadController {

	// @ModelAttribute
	// public void ajaxAttribute(WebRequest request, Model model) {
	// model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(request));
	// }

	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public String fileUploadForm() {
		return "FileUploadForm";
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String processUpload(@RequestParam MultipartFile file, Model model)
			throws IOException {

		model.addAttribute("fileName", file.getOriginalFilename());
		// save file in the disk
		File f = new File("/home/gayan/" + file.getOriginalFilename());
		file.transferTo(f);
		return "FileUploadSuccess";

	}

//	@RequestMapping(value = "/download", method = RequestMethod.GET)
//	public String helloWorld(Model model) {
//		// ModelAndView mav = new ModelAndView();
//		// Model.setViewName("fileTransfer");
//		File f = new File("/home/gayan/check");
//		// Model.addObject("file", f.getName());
//		model.addAttribute("file", f);
//		return "FileDownload";
//	}

	// /**
	// * download
	// */
	// public ModelAndView download(HttpServletRequest request,
	// HttpServletResponse response) throws Exception {
	// int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
	//
	// Files file = this.filesService.find(id);
	//
	// response.setContentType(file.getType());
	// response.setContentLength(file.getFile().length);
	// response.setHeader("Content-Disposition","attachment; filename=\"" +
	// file.getFilename() +"\"");
	//
	// FileCopyUtils.copy(file.getFile(), response.getOutputStream());
	//
	// return null;
	//
	// }

	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public void add(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// int id = ServletRequestUtils.getRequiredIntParameter(request, "id");
		//
		// Files file = this.filesService.find(id);
		File file = new File("/home/gayan/check");	

//        response.setContentLength(file.getFile().length);
        System.out.println("file name:"+file.getName());
        response.setHeader("Content-Disposition","attachment; filename=\"" + file.getName() +"\"");

        FileCopyUtils.copy(getBytesFromFile(file), response.getOutputStream());

	}
	
	// Returns the contents of the file in a byte array.
	public byte[] getBytesFromFile(File file) throws IOException {
	    InputStream is = new FileInputStream(file);

	    // Get the size of the file
	    long length = file.length();

	    // You cannot create an array using a long type.
	    // It needs to be an int type.
	    // Before converting to an int type, check
	    // to ensure that file is not larger than Integer.MAX_VALUE.
	    if (length > Integer.MAX_VALUE) {
	        // File is too large
	    }

	    // Create the byte array to hold the data
	    byte[] bytes = new byte[(int)length];

	    // Read in the bytes
	    int offset = 0;
	    int numRead = 0;
	    while (offset < bytes.length
	           && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
	        offset += numRead;
	    }

	    // Ensure all the bytes have been read in
	    if (offset < bytes.length) {
	        throw new IOException("Could not completely read file "+file.getName());
	    }

	    // Close the input stream and return bytes
	    is.close();
	    return bytes;
	}
}
